<template>
	<u-upload ref="upload" :action="action" :max-size="5 * 1024 * 1024" max-count="1" :before-upload="beforeUpload"
		:custom-btn="true" :show-progress="true" :multiple="false" :deletable="true" :form-data="formData" @on-success="success">
		<u-avatar slot="addBtn" :src="vuex_user.avatar_url" size="140"></u-avatar>
	</u-upload>
</template>

<script>
	let _this = {};
	export default {
		data() {
			return {
				action: 'http://www.example.com/upload',
				formData: {},
				upFileName: '',
			}
		},
		created() {
			_this = this;
		},
		methods: {
			/**
			 * 小程序中this可能会丢失
			 * 小程序中file里面是path，H5端是path
			 */
			async beforeUpload(index, list) {
				// list 文件数组
				// console.log(list)
				
				const {file} = list[0];
				// #ifdef H5
				const fileName = file.name;
				// #endif
				
				// #ifndef H5
				const fileName = file.path;
				// #endif
				
				console.log(file)
				
				// 唯一文件名
				const suxx = fileName.slice(fileName.lastIndexOf('.'));
				const upFileName = _this.$u.guid(20) + suxx;
				_this.upFileName = upFileName;
				console.log(upFileName);
				
				
				// 请求api获取token
				const ossToken = await _this.$u.api.authOss();
				console.log(ossToken);
				
				
				// 上传的参数
				_this.formData = {
					'key': upFileName, //上传后的文件名
					'policy': ossToken.policy,
					'OSSAccessKeyId': ossToken.accessid,
					'success_action_status' : '200',
					'signature': ossToken.signature,
				}
				_this.action = ossToken.host
				return true;
			},
			/**
			 * 上传成功回调函数
			 * 请求api更新头像，更新缓存
			 */
			async success() {
				// 移除预览区域图片
				this.$refs.upload.remove(0);
				await this.$u.api.userAvatar({
					avatar: this.upFileName
				});
				this.$u.toast('更新成功');
				this.$u.utils.updateUser();
			},
			
		},
	}
</script>